// ignore_for_file: use_build_context_synchronously

import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_utils/format_util.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

import '../../hj_model/acg/comic_chapters_model.dart';
import '../../hj_model/cartoon_media_info.dart';
import '../../hj_model/user/wallet_model_entity.dart';
import '../../hj_utils/api_service/mine_service.dart';
import '../../hj_utils/global.dart';
import '../../routers/jump_router.dart';
import '../../tools_base/debug_log.dart';
import '../../tools_base/global_store/store.dart';
import '../../tools_base/loading/loading_alert_widget.dart';
import '../../tools_base/net/api_exception.dart';
import '../../tools_base/net/base_resp_bean.dart';

///购买漫画/小说弹窗
class ComicBuyAlert extends StatefulWidget {
  //// 返回值:  1 购买单集， 2 购买全集，null 啥都没购买
  static Future<int?> show({
    ComicChapterInfo? curModel, // 单集数据
    CartoonMediaInfo? mediaInfo, // 全集数据
  }) async {
    return await Get.bottomSheet(ComicBuyAlert(
      mediaInfo: mediaInfo,
      curModel: curModel,
    ));
  }

  final ComicChapterInfo? curModel; // 单集数据
  final CartoonMediaInfo? mediaInfo; // 全集数据

  ComicBuyAlert({
    super.key,
    this.curModel,
    this.mediaInfo,
  });

  @override
  State<StatefulWidget> createState() {
    return _ComicBuyAlertState();
  }
}

enum BuyTypeUI {
  all, // 整套购买
  only, // 单节购买
  allOrOnly, //整套和单节购买
}

class _ComicBuyAlertState extends State<ComicBuyAlert> {
  bool isBuying = false;

  // 1 整套购买， 2 单节购买， 3 整套和单节购买
  BuyTypeUI get buyTypeValue {
    return BuyTypeUI.all;
    if (widget.mediaInfo != null && widget.curModel == null) {
      return BuyTypeUI.all;
    }
    if (widget.mediaInfo == null && widget.curModel != null) {
      return BuyTypeUI.only;
    }
    if (widget.mediaInfo != null && widget.curModel != null) {
      return BuyTypeUI.allOrOnly;
    }
    return BuyTypeUI.only;
  }

  int get discountPrice {
    if (widget.mediaInfo != null) {
      int price = (widget.mediaInfo?.contentsPrice ?? 0) - (widget.mediaInfo?.price ?? 0);
      return max(0, price);
    }
    return 0;
  }

  String get priceTitle {
    if (buyTypeValue == BuyTypeUI.all) {
      return "${widget.mediaInfo?.price}";
    }
    return "${widget.curModel?.price}";
  }

  WalletModelEntity? get wallet => globalStore.getWallet();

  bool get isVip => globalStore.isVIP();

  @override
  void initState() {
    super.initState();
    globalStore.refreshWallet().then((value) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  ///购买作品
  _buyProduct(bool isAll) async {
    if (isBuying) return;
    isBuying = true;
    setState(() {});
    try {
      int productType = 19; //19 购买整本，25 购买子集
      String? productID = widget.mediaInfo?.id ?? widget.curModel?.mediaId;
      if (!isAll) {
        productType = 25;
        productID = widget.curModel?.id;
      }
      LoadingAlertWidget.show();
      BaseRespBean data = await MineService.postBuyVideo(productID, productType);
      LoadingAlertWidget.cancel();
      if (data.isSuccess) {
        globalStore.refreshWallet();
        showToast("购买成功");
        if (isAll) {
          Get.back(result: 2);
        } else {
          Get.back(result: 1);
        }
      } else {
        if (data.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          //showToast("网络异常, 支付失败");
        }
      }
    } on DioException catch (e) {
      LoadingAlertWidget.cancel();
      var error = e.error;
      if (error is ApiException) {
        if (error.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast(error.message);
        }
      } else {
        showToast(e.toString());
      }

      debugLog('productBuy', e.toString());
    } catch (e) {
      LoadingAlertWidget.cancel();
      debugLog('postBuyVideo', e.toString());
    }
    isBuying = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.bottomCenter,
      child: Material(
        color: Colors.transparent,
        child: Consumer<GlobalStore>(
          builder: (context, _, child) {
            bool enough = (_.wallet?.amount ?? 0) >= (widget.mediaInfo?.price ?? 0);
            return _buildNormal(enough);
          },
        ),
      ),
    );
  }

  Widget _buildNormal(bool enough) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
      decoration: BoxDecoration(
        color: Color(0xff030F18),
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 36,
            height: 5,
            child: DecoratedBox(
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(.2),
                borderRadius: BorderRadius.circular(3),
              ),
            ),
          ),
          18.sizeBoxH,
          Text(
            '购买作品',
            style: TextStyle(
              color: Color(0xE5ffffff),
              fontSize: 20,
              fontWeight: FontWeight.w500,
            ),
          ),
          36.sizeBoxH,
          Row(
            children: [
              Text(
                '作品解锁',
                style: TextStyle(
                  color: Color(0xE5ffffff),
                  fontSize: 14,
                ),
              ),
              Spacer(),
              GestureDetector(
                onTap: () => jumpToWalletPage(tabPosition: 1),
                child: Row(
                  children: [
                    Image.asset(
                      'coin_x.webp'.commonImgPath,
                      width: 24,
                      height: 24,
                    ),
                    10.sizeBoxW,
                    Text(
                      '${widget.mediaInfo?.price ?? 0} 金币',
                      style: TextStyle(
                        color: Color(0xffFF9000),
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
          18.sizeBoxH,
          Divider(
            height: 0.5,
            color: Colors.white.withOpacity(.05),
          ),
          18.sizeBoxH,
          Row(
            children: [
              Text(
                '我的金币',
                style: TextStyle(
                  color: Color(0xE5ffffff),
                  fontSize: 14,
                ),
              ),
              Spacer(),
              Row(
                children: [
                  Text(
                    '${GlobalStore().wallet?.amount?.toDouble().fixed(2) ?? 0}',
                    style: TextStyle(
                      color: Color(0xE5ffffff),
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  12.sizeBoxW,
                  InkWell(
                    onTap: () => jumpToWalletPage(tabPosition: 1),
                    child: Text(
                      '充值',
                      style: TextStyle(
                          color: Color(0xffA4634D),
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                          decoration: TextDecoration.underline,
                          decorationColor: Color(0xffA4634D)),
                    ),
                  ),
                ],
              ),
            ],
          ),
          18.sizeBoxH,
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              if (enough) {
                _buyProduct(true);
              } else {
                jumpToWalletPage(tabPosition: 1);
              }
            },
            child: Container(
              width: double.infinity,
              height: 47,
              decoration: BoxDecoration(color: Color(0xffE1351F), borderRadius: BorderRadius.circular(3)),
              alignment: Alignment.center,
              child: Text(
                enough ? '${widget.mediaInfo?.price ?? 0}金币/立即支付' : '余额不足，前往充值',
                style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSimpleWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          buyTypeValue == BuyTypeUI.all ? "温馨提示" : "温馨提示",
          style: TextStyle(
            fontSize: 20,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
        24.sizeBoxH,
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(
              "acg_coin.png".commonImgPath,
              width: 24,
              height: 24,
            ),
            15.sizeBoxW,
            Text(
              priceTitle + '金币',
              style: const TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ],
        ),
        12.sizeBoxH,
        Text(
          "解锁即可查看精彩内容",
          overflow: TextOverflow.ellipsis,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            color: Colors.white,
            height: 2.0,
          ),
        ),
        12.sizeBoxH,
        Text(
          "当前余额: ${globalStore.wallet?.amount}金币",
          overflow: TextOverflow.ellipsis,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 16,
            color: Colors.white,
            height: 2.0,
          ),
        ),
        12.sizeBoxH,
        Container(
          height: 42,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: InkWell(
            onTap: () async {
              _buyProduct(buyTypeValue == BuyTypeUI.all);
            },
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Color(0xff3E64EA),
                borderRadius: BorderRadius.circular(30),
              ),
              child: Text(
                "立即解锁",
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAllOrOnlyWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          "温馨提示",
          style: TextStyle(
            fontSize: 20,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
        24.sizeBoxH,
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(
              "acg_coin.png".commonImgPath,
              width: 24,
              height: 24,
            ),
            15.sizeBoxW,
            Text(
              priceTitle + '金币解锁/章',
              style: const TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ],
        ),
        12.sizeBoxH,
        if (discountPrice > 0)
          Container(
            padding: EdgeInsets.only(bottom: 12),
            child: Text(
              "整本解锁更优惠 立省$discountPrice金币",
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.white,
                height: 2.0,
              ),
            ),
          ),
        Text(
          "当前余额: ${globalStore.wallet?.amount}金币",
          overflow: TextOverflow.ellipsis,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 16,
            color: Colors.white,
            height: 2.0,
          ),
        ),
        18.sizeBoxH,
        _buildDoubleButton(),
      ],
    );
  }

  Widget _buildDoubleButton() {
    return Container(
      height: 42,
      child: Row(
        children: [
          Expanded(
            flex: 114,
            child: InkWell(
              onTap: () async {
                _buyProduct(false);
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(30),
                ),
                child: Text(
                  "单章解锁",
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ),
          12.sizeBoxW,
          Expanded(
            flex: 144,
            child: InkWell(
              onTap: () async {
                _buyProduct(true);
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Color(0xff3E64EA),
                  borderRadius: BorderRadius.circular(30),
                ),
                child: Text(
                  "整本解锁",
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
